<?php
namespace app\admin\model;

use think\Model;
use think\Log;
use app\common\lib\exception\ApiException;
class SystemConfig extends Model{
    /**
     * 获取配置类型
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed
     */
    public function getConfigTypeAttr($value){
        $config_type = [
            1 => '输入框',
            2 => '单选',
            3 => '复选',
            4 => '下拉菜单',
            5 => '文本域',
            6 => '附件'
        ];
        return $config_type[$value];
    }

    /**
     * 获取配置分类
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed
     */
    public function getConfigCategoryAttr($value){
        $config = config('system.system_config');
       return $config[$value];
    }

    /**
     * 获取所有配置信息
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array
     */
    public function getAll($where = ''){
        $keywords = input('post.keywords');
        if(!empty($keywords)){
            $where = ['ch_name|en_name|config_type|config_category'
            => ['like', "%$keywords%"]];
        }

        try{
            $data = $this
                ->where($where)
                ->order('config_category')
                ->select();
            if(!empty($data)){
                foreach ($data as $key => $val){
                    $data[$key] = $val->toArray();
                }
            }
            
            return $data;
        }catch (\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }

    /**
     * 获取配置总记录数
     * @author 王柯 <wangke.email@foxmail.com>
     * @return void
     */
    public function getCount($where = ''){
        $keywords = input('post.keywords');
        if(!empty($keywords)){
            $where = ['ch_name|en_name|config_type|config_category'
            => ['like', "%$keywords%"]];
        }

        try{
            $count = $this
                ->where($where)
                ->count();
            return $count;
        }catch (\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }

    /**
     * 查询单条数据
     * @param $id int 配置id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array
     */
    public function getOne($id){
        try{
            $data = $this
                ->where('id='.$id)
                ->find()
                ->toArray();
            return $data;
        }catch (\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }
}